package com.sihai.ehr.web.action.user;

import com.sihai.core.LimitedList;
import com.sihai.core.beans.BeanInject;
import com.sihai.ehr.model.biz.EmployeeinfoBase;
import com.sihai.ehr.model.sys.Organization;
import com.sihai.ehr.model.sys.User;
import com.sihai.ehr.service.EmployeeService;
import com.sihai.ehr.service.OrganizationService;
import com.sihai.ehr.service.UserService;
import com.sihai.ehr.web.action.EHRAction;
import com.sihai.ehr.web.pojo.StaffSearchPojo;
import com.sihai.ehr.web.pojo.UserSetupPojo;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;

import java.util.Iterator;
import java.util.List;

@Results({@Result(name = "main", location = "user_main.jsp"),
        @Result(name = "list", location = "user_list.jsp"),
        @Result(name = "add", location = "user_add.jsp"),
        @Result(name = "edit", location = "user_modify.jsp"),
        @Result(name = "select", location = "user_select.jsp")
})
public class UserAction extends EHRAction {

    @BeanInject
    private OrganizationService organizationService;
    @BeanInject
    private UserService userService;
    @BeanInject
    private EmployeeService employeeService;

    private List<Organization> organizations;
    //搜索对象
    private StaffSearchPojo search;

    //职务ID
    private Long dutyId;

    private LimitedList<UserSetupPojo> userSetupPojos;

    private User user;

    private UserSetupPojo pojo;

    private Long id;//user id;

    private String updateResult;//更新结果

    private String userIds;//删除的user id;

    private String name;//选择的员工姓名

    //#add.wxn#2013.02.02
    private String selection_type;//单选或多选
    private LimitedList<User> users;

    private Boolean exist;

    @Override
    @Action("/user/setup")
    public String execute() throws Exception {
        this.listAction = "/user/user_list.xhtml";
        this.listTitle = "账号设置";

        organizations = organizationService.findChildren(null, true, null, null);
        if (organizations != null && organizations.size() > 0) {
        	if(getCurrentUserId() > 0){
            	Long topOrgId = getCurrentUser().getWork().getOrganization().getTopOrganization().getId();
            	Iterator<Organization> it = organizations.iterator();
            	while(it.hasNext()){
            		Organization o = it.next();
            		if(o.getId() != topOrgId){
            			it.remove();
            		}
            	}
            }
            organizationId = organizations.get(0).getId();
        }
        showChildOrg = true;
        return "main";
    }

    @Action("/user/user_list")
    public String list() throws Exception {

        search = new StaffSearchPojo();
        search.setDepartment(organizationId);
        search.setDuty(dutyId);

        //userSetupPojos = userService.findUserByid(search, "1", createLimit(), createSorter());
        users = userService.findByTopOrganizations(organizationId, createLimit(), createSorter());
        //分页
        this.setPageUrl("/user/user_list.xhtml");
        this.paging(users);
        return "list";
    }

    @Action("/user/user_add")
    public String add() throws Exception {
        if(id!=null){
            EmployeeinfoBase baseinfo=employeeService.getEmployeeinfoBase(id);
            name=baseinfo.getName();
        }
        return "add";
    }

    @Action("/user/user_create")
    public String create() throws Exception {
        userService.saveUser(user);
        return execute();
    }

    @Action("/user/user_edit")
    public String edit() throws Exception {
        //pojo = userService.getUserById(id);
        user = userService.getUser(id);
        return "edit";
    }

    @Action(value = "/user/user_update", results = {
            @Result(name = "success", type = "json", params = {"root", "updateResult"})
    })
    public String update() throws Exception {
        //updateResult = userService.updateUser(pojo);
        if(user == null || user.getId() == null){
            updateResult = "fail";
            return SUCCESS;
        }
        User u = userService.getUser(user.getId());
        if(u == null){
            updateResult = "fail";
            return SUCCESS;
        }
        //不验证旧密码
        /*if(!StringUtils.equals(u.getPassword(), getParameter("old_password"))){
            updateResult = "wrong_password";
            return SUCCESS;
        }*/
        u.setPassword(getParameter("new_password"));
        userService.saveUser(u);
        updateResult = "success";
        return SUCCESS;
    }

    @Action(value="/user/user_delete")
    public String delete() throws Exception {
        if(StringUtils.isBlank(userIds)) {
            return list();
        }
        userService.removeUser(userIds);
        return list();
    }

    //选择员工
    //add.wxn#2013.02.04
    @Action("/user/select")
    public String find() throws Exception {
        users = userService.findByTopOrganizations(organizationId, createLimit(), createSorter());
        //分页
        this.setPageUrl("user/select.xhtml");
        this.paging(users);
        return "select";
    }


    @Action(value = "/ajax/check_user_account", results = {@Result(name = "success", type = "json", params = {"root", "exist"})
    })
    public String checkByAccount() {
        try{
            exist = userService.isExistByUserName(getParameter("account"));
        }catch (Exception e){
            e.printStackTrace();
        }
        return SUCCESS;
    }
    @Action(value = "/ajax/check_user_work", results = {@Result(name = "success", type = "json", params = {"root", "exist"})
    })
    public String checkByWork() {
        try{
            exist = userService.isExistByWorkId(NumberUtils.createLong(getParameter("workId")));
        }catch (Exception e){
            e.printStackTrace();
        }
        return SUCCESS;
    }


    public StaffSearchPojo getSearch() {
        return search;
    }

    public void setSearch(StaffSearchPojo search) {
        this.search = search;
    }

    public Long getDutyId() {
        return dutyId;
    }

    public void setDutyId(Long dutyId) {
        this.dutyId = dutyId;
    }

    public LimitedList<UserSetupPojo> getUserSetupPojos() {
        return userSetupPojos;
    }

    public void setUserSetupPojos(LimitedList<UserSetupPojo> userSetupPojos) {
        this.userSetupPojos = userSetupPojos;
    }

    public List<Organization> getOrganizations() {
        return organizations;
    }

    public void setOrganizations(List<Organization> organizations) {
        this.organizations = organizations;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public UserSetupPojo getPojo() {
        return pojo;
    }

    public void setPojo(UserSetupPojo pojo) {
        this.pojo = pojo;
    }

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUpdateResult() {
        return updateResult;
    }

    public void setUpdateResult(String updateResult) {
        this.updateResult = updateResult;
    }

    public String getUserIds() {
        return userIds;
    }

    public void setUserIds(String userIds) {
        this.userIds = userIds;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getSelection_type() {
        return selection_type;
    }

    public void setSelection_type(String selection_type) {
        this.selection_type = selection_type;
    }

    public LimitedList<User> getUsers() {
        return users;
    }

    public Boolean getExist() {
        return exist;
    }

    public void setExist(Boolean exist) {
        this.exist = exist;
    }
}
